package com.atguigu.tingshu.album.receiver;


import com.atguigu.tingshu.album.mapper.AlbumStatMapper;
import com.atguigu.tingshu.album.mapper.TrackStatMapper;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.model.album.AlbumStat;
import com.atguigu.tingshu.model.album.TrackStat;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AlbumReceriver {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AlbumStatMapper albumStatMapper;
    @Autowired
    private TrackStatMapper trackStatMapper;


    /**
     * 接收专辑播放统计消息
     *
     * @param trackStatMqVo
     * @param message
     * @param channel
     */
    @Transactional
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true"),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateAlbumStat(TrackStatMqVo trackStatMqVo, Message message, Channel channel) {

        if (trackStatMqVo != null) {
            log.info("[专辑服务]监听到声音播放统计消息：{}", trackStatMqVo);
            String key = RedisConstant.BUSINESS_PREFIX + "db:" + trackStatMqVo.getBusinessNo();
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstant.ORDER_TRADE_EXPIRE, TimeUnit.MINUTES);
            if (flag) {
                //数据的保存操作
                try {
                    //获取基本数据
                    Long albumId = trackStatMqVo.getAlbumId();
                    Long trackId = trackStatMqVo.getTrackId();
                    String statType = trackStatMqVo.getStatType();
                    Integer count = trackStatMqVo.getCount();
                    //判断播放还是评论
                    if (SystemConstant.TRACK_STAT_PLAY.equals(statType)) {
                        //更新专辑统计表
                        LambdaUpdateWrapper<AlbumStat> albumStatLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        albumStatLambdaUpdateWrapper.eq(AlbumStat::getAlbumId, albumId);
                        albumStatLambdaUpdateWrapper.eq(AlbumStat::getStatType, SystemConstant.ALBUM_STAT_PLAY);
                        albumStatLambdaUpdateWrapper.setSql("stat_num = stat_num +" + count);
                        albumStatMapper.update(null, albumStatLambdaUpdateWrapper);
                        //更新声音统计表
                        LambdaUpdateWrapper<TrackStat> trackStatLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        trackStatLambdaUpdateWrapper.eq(TrackStat::getTrackId, trackId);
                        trackStatLambdaUpdateWrapper.eq(TrackStat::getStatType, SystemConstant.TRACK_STAT_PLAY);
                        trackStatLambdaUpdateWrapper.setSql("stat_num = stat_num +" + count);
                        trackStatMapper.update(null, trackStatLambdaUpdateWrapper);
                    }
                    if (SystemConstant.TRACK_STAT_COMMENT.equals(statType)){
                        //更新专辑统计表
                        LambdaUpdateWrapper<AlbumStat> albumStatLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        albumStatLambdaUpdateWrapper.eq(AlbumStat::getAlbumId, albumId);
                        albumStatLambdaUpdateWrapper.eq(AlbumStat::getStatType, SystemConstant.ALBUM_STAT_COMMENT);
                        albumStatLambdaUpdateWrapper.setSql("stat_num = stat_num +" + count);
                        albumStatMapper.update(null, albumStatLambdaUpdateWrapper);
                        //更新声音统计表
                        LambdaUpdateWrapper<TrackStat> trackStatLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                        trackStatLambdaUpdateWrapper.eq(TrackStat::getTrackId, trackId);
                        trackStatLambdaUpdateWrapper.eq(TrackStat::getStatType, SystemConstant.TRACK_STAT_COMMENT);
                        trackStatLambdaUpdateWrapper.setSql("stat_num = stat_num +" + count);
                        trackStatMapper.update(null, trackStatLambdaUpdateWrapper);
                    }
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (Exception e) {
                    log.error("[专辑服务]:专辑和声音的统计数据的保存错误{}", e);
                    redisTemplate.delete(key);
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                }

            }

        }

    }
}
